package com.orangelife.mobile.login.activity;

import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bonree.agent.android.harvest.Statistics;
import com.common.jump.LocationJumper;
import com.common.sp.AppSp;
import com.common.sp.CommSp2;
import com.common.sp.UserSp;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.util.CountDownHandler;
import com.curry.android.util.PhoneCallUtil;
import com.curry.android.util.StringUtil;
import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.common.jump.CommonJumper;
import com.orangelife.mobile.verify.biz.SmsHttpBiz;
import com.thirdsdk.jpush.JPushTagHelper;
import com.orangelife.mobile.login.biz.LoginBiz;
import com.orangelife.mobile.login.biz.LoginHttpBiz;
import com.orangelife.mobile.main.biz.JumpUtil;
import com.orangelife.mobile.util.BLog;
import com.thirdsdk.zhugeio.ZhugeIOHelper;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

import org.json.JSONObject;

/**
 * 新版登录
 * Created by luxiaojuan on 2015/11/16.Mod by wgf on 16080801.
 *
 * @author lxj
 */
public class Login2Activity extends OrangeLifeBaseActivity {

    @Bind(R.id.etPhone)
    EditText etPhone;
    @Bind(R.id.tvCode)
    TextView tvCode;
    @Bind(R.id.rlCode)
    RelativeLayout rlCode;
    @Bind(R.id.etCode)
    EditText etCode;
    @Bind(R.id.etPwd)
    EditText etPwd;
    @Bind(R.id.tvGetCode)
    TextView tvGetCode;
    @Bind(R.id.tvVoiceCode)
    TextView tvVoiceCode;
    @Bind(R.id.btnLogin)
    Button btnLogin;
    @Bind(R.id.llVoiceCode)
    LinearLayout llVoiceCode;
    @Bind(R.id.llCallCS)
    LinearLayout llCallCS;
    @Bind(R.id.tvCS)
    TextView tvCS;
    public static final int WHAT_VOICE_CODE = 66;
    public static final int WHAT_SMS_CODE = 67;
    public static final int WHAT_LOGIN = 68;
    public static final int WHAT_VOICE_CODE_STATE = 69;
    private boolean isUsePassword = false;
    /**
     * 是否已经请求过一次短信验证码
     */
    private boolean hasSentSmsVerify;

    /**
     * Activit 名称
     **/
    final String MODULE_NAME = "/app/guidePage/register";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login3);
        ButterKnife.bind(this);
        requestVoiceCodeState();
        initView();
        findView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Statistics.onPageEnd("Login1", "LoginPage");
    }

    private void initView() {
        // 为了保险起见，这边再做一次显示或者不显示
        tvCode.setText("验证码");
        etCode.setVisibility(View.VISIBLE);
        etPwd.setVisibility(View.GONE);
        tvGetCode.setVisibility(View.VISIBLE);
        tvCS.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tvCS.getPaint().setAntiAlias(true);//抗锯齿
        if (AppSp.getVoiceCodeState()) {
            llVoiceCode.setVisibility(View.VISIBLE);
            llVoiceCode.setClickable(false); //刚进入时可看不可点击
            llCallCS.setVisibility(View.GONE);
        } else {
            llVoiceCode.setVisibility(View.GONE);
            llCallCS.setVisibility(View.VISIBLE);
        }
    }


    private void setVoiceCodeState(boolean shouldShow) {
        AppSp.setVoiceCodeState(shouldShow);
        if (shouldShow) {
            llCallCS.setVisibility(View.GONE);
            llVoiceCode.setVisibility(View.VISIBLE);
            llVoiceCode.setClickable(true);
        } else {
            llVoiceCode.setVisibility(View.GONE);
            llCallCS.setVisibility(View.VISIBLE);
        }
    }

    private void findView() {
        rlCode.setOnClickListener(listener);
        btnLogin.setOnClickListener(listener);
        tvGetCode.setOnClickListener(listener);
        tvVoiceCode.setOnClickListener(listener);
        tvCS.setOnClickListener(listener);
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                //语音验证码
                case R.id.tvVoiceCode:
                    isSendSms = false;
                    requestVerifyCode(false);
                    dataTrackClick("btnGetVerificationCode", null);
                    break;
                case R.id.rlCode:
                    switchPasswordView();
                    break;
                case R.id.tvGetCode:
                    isSendSms = true;
                    requestVerifyCode(true);
                    break;
                case R.id.tvCS:
                    PhoneCallUtil.getInstances().callPhone(Login2Activity.this, CommSp2.getCustomerServicePhone(), getApplicationContext().getResources().getString(R.string.customer_phone));
                    break;
                case R.id.btnLogin:
                    requestLogin();
                    break;
            }
        }
    };

    /**
     * 切换登录口令模式，密码或验证码
     */
    private void switchPasswordView() {
        if ("验证码".equals(tvCode.getText().toString())) {
            tvCode.setText("密码");
            isUsePassword = true;
            etCode.setVisibility(View.GONE);
            etPwd.setVisibility(View.VISIBLE);
            tvGetCode.setVisibility(View.GONE);
        } else {
            tvCode.setText("验证码");
            isUsePassword = false;
            etCode.setVisibility(View.VISIBLE);
            etPwd.setVisibility(View.GONE);
            tvGetCode.setVisibility(View.VISIBLE);
        }
    }

    private void requestVerifyCode(boolean isSms) {
        disableCode();
        String phone = etPhone.getText().toString();
        if (LoginBiz.validatePhoneNum(phone, this)) {
            showDialog(this);
            if (isSms) {
                requestSmsVerifyCode(phone);
            } else {
                requestVoiceVerifyCode(phone);
            }
            startTimer();
        } else {
            enableCode();
        }
    }


    private void requestSmsVerifyCode(String phone) {
        SmsHttpBiz.getSmsVerifyCode(phone, hasSentSmsVerify, WHAT_SMS_CODE, mLoginHandler);
        hasSentSmsVerify = true;
    }

    private void requestVoiceVerifyCode(String phone) {
        SmsHttpBiz.getVoiceVerifyCode(phone, WHAT_VOICE_CODE, mLoginHandler);
    }

    private void requestLogin() {
        String phone = etPhone.getText().toString();
        if (LoginBiz.validatePhoneNum(phone, this)) {
            if (isUsePassword) {
                String password = etPwd.getText().toString();
                if (LoginBiz.validatePassword(password, isUsePassword)) {
                    showDialog(this);
                    LoginHttpBiz.loginWithPassword(phone, password, WHAT_LOGIN, mLoginHandler);
                }
            } else {
                String verifyCode = etCode.getText().toString();
                if (LoginBiz.validatePassword(verifyCode, isUsePassword)) {
                    showDialog(this);
                    LoginHttpBiz.loginWithVerifyCode(phone, verifyCode, WHAT_LOGIN, mLoginHandler);
                }
            }
        }
    }

    private void requestVoiceCodeState() {
        LoginHttpBiz.voiceCodeState(WHAT_VOICE_CODE_STATE, mLoginHandler);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            CurryApplication.getInstance().exit();
            finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void jumpWithJPushUri() {
        if (getIntent().getBooleanExtra("jPush", false)) {/*代表推送*/
            Parcelable parcelable = getIntent().getParcelableExtra("uri");
            if (parcelable != null) {
                JumpUtil.jumpActivity(this, parcelable.toString(), true);
            }
        }
    }

    public void jumpMain(String commID) {
        if (StringUtil.isContainBlank(commID)) {/*未选择城市则先跳转到城市列表*/
            LocationJumper.jumpToSelectCity(this);
        } else {
            CommonJumper.jumpToMain(this);
        }
    }

    public void saveLoginInfo(Map<String, Object> map) {
        String loginID = String.valueOf(map.get("loginID"));
        String phoneNumber = String.valueOf(map.get("phone"));
        String nickname = String.valueOf(map.get("nickname"));

        UserSp.setAccessToken(String.valueOf(map.get("accessToken")));
        UserSp.setLoginID(loginID);
        UserSp.setRegPhone(phoneNumber);
        UserSp.setNickname(nickname);
        UserSp.setProtraitImg(String.valueOf(map.get("protraitImg")));
        UserSp.setPoint(String.valueOf(map.get("score")));
        setTokenToHeader();
        setJPushTag(phoneNumber);
        BLog.getInstance().setMemberID(loginID);
    }

    private void setTokenToHeader() {
        CurryApplication.getInstance().setAccessToken();
    }

    private void setJPushTag(String phone) {
        JPushTagHelper.getInstance().setContext(this);
        JPushTagHelper.getInstance().setAlias(phone);
    }

    private CountDownHandler countDownHandler;
    /**
     * 默认发送短信
     */
    private boolean isSendSms = true;

    private void startTimer() {
        if (countDownHandler == null) {
            countDownHandler = new CountDownHandler();
            countDownHandler.isOnlySecond(true);
            countDownHandler.isUseCustomCountDownInfo(true);
            countDownHandler.setOnCountDownTimerFinishedListener(new CountDownHandler.OnCountDownTimerFinishedListener() {
                @Override
                public void onFinish() {
                    enableCode();
                }

                @Override
                public void onCountDown(String currentSecond) {
                    setCountDownViewOnCounting(currentSecond);
                }
            });
        }
        countDownHandler.startTimer("60");
    }

    private void setCountDownViewOnCounting(String currentSecond) {
        String s = getResources().getString(R.string.count_down_info, currentSecond);
        if (isSendSms) {
            tvGetCode.setText(s);
            etCode.setHint("请输入短信验证码");
        } else {
            tvVoiceCode.setText(s);
            etCode.setHint("请输入语音验证码");
        }
    }

    private void disableCode() {
        etCode.setText("");
        tvGetCode.setEnabled(false);
        tvVoiceCode.setEnabled(false);
    }

    private void enableCode() {
        tvGetCode.setEnabled(true);
        tvVoiceCode.setEnabled(true);
        tvVoiceCode.setText(getResources().getString(
                R.string.voice_code));
        tvGetCode.setText(getResources().getString(R.string.send_again));
    }

    private LoginHandler mLoginHandler = new LoginHandler(this);

    private static class LoginHandler extends Handler {
        private WeakReference<Login2Activity> weakReference = null;

        public LoginHandler(Login2Activity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            Login2Activity act = weakReference.get();
            if (act == null) {
                return;
            }
            act.closeDialog();
            switch (msg.what) {
                case Login2Activity.WHAT_VOICE_CODE:
                    SmsHttpBiz.handleVerifyCode(msg.obj, act.getResources().getString(R.string.send_voice_fail), act.getResources().getString(
                            R.string.send_voice_success));
                    break;
                case Login2Activity.WHAT_SMS_CODE:
                    SmsHttpBiz.handleVerifyCode(msg.obj, act.getResources().getString(R.string.send_sms_fail), act.getResources().getString(
                            R.string.send_sms_success));
                    break;
                case Login2Activity.WHAT_LOGIN:/* 密码登录 */
                    Map<String, Object> map = LoginHttpBiz.handleLogin(msg.obj, act.getResources().getString(R.string.login_fail), null);
                    if (map != null) {
                        act.saveLoginInfo(map);
                        String commID = CommSp2.getCommID();
                        act.jumpMain(commID);
                        act.jumpWithJPushUri();
                        act.etPhone.setText("");
                        act.etPwd.setText("");
                        act.etCode.setText("");
                    }
                    break;
                case Login2Activity.WHAT_VOICE_CODE_STATE:
                    //wiki文档未更新 voiceType   0：不开启语音  1：开启
                    Map<String, Object> entity = OrangeDataHandler.getMapWithEntityNoGson((JSONObject) msg.obj);
                    if (entity == null) {
                        return;
                    }
                    if (String.valueOf(entity.get("voiceType")).equals("1")) {
                        act.setVoiceCodeState(true);
                    } else {
                        act.setVoiceCodeState(false);
                    }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLoginHandler.removeCallbacksAndMessages(null);
        if (countDownHandler != null) {
            countDownHandler.stopTimer();
        }
    }
}
